package com.example.translator;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class ExportService {
    public static void exportToCSV(List<FileInfo> fileInfos, File outputFile) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8))) {
            
            // 写入CSV头部
            writer.write("序号,原文件名,翻译后文件名,状态");
            writer.newLine();
            
            // 写入数据行
            for (int i = 0; i < fileInfos.size(); i++) {
                FileInfo fileInfo = fileInfos.get(i);
                String status;
                
                if (fileInfo.isTranslationStatus()) {
                    status = "已翻译";
                } else if (!fileInfo.getErrorMsg().isEmpty()) {
                    status = "翻译失败";
                } else {
                    status = "待翻译";
                }
                
                // 使用CSV作为分隔符，避免是CSV中不常见的字符
                writer.write(String.format("%d,%s,%s,%s",
                        i + 1,
                        escapeCsv(fileInfo.getFullOriginalName()),
                        escapeCsv(fileInfo.getTranslatedName()),
                        status));
                writer.newLine();
            }
        }
    }

    private static String escapeCsv(String value) {
        if (value == null) {
            return "";
        }
        
        // 如果包含逗号、引号或换行符，则需要用引号包裹
        if (value.contains(",") || value.contains("\"") || value.contains("\n") || value.contains("\r")) {
            // 替换引号为两个引号
            return "\"" + value.replace("\"", "\"\"") + "\"";
        }
        
        return value;
    }
}
